package com.fyp.ptma.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.fyp.ptma.android.client.Apk;
import com.fyp.ptma.android.client.ApkReader;
import com.fyp.ptma.dao.service.iservice.IApplicationService;
import com.fyp.ptma.dao.service.iservice.IDownloaderService;
import com.fyp.ptma.dao.service.iservice.IUserService;
import com.fyp.ptma.model.Application;
import com.fyp.ptma.model.ApplicationVersion;
import com.fyp.ptma.model.ApplicationVersionPk;
import com.fyp.ptma.model.Downloader;
import com.fyp.ptma.model.User;
import com.fyp.ptma.property.PropertyFile;

@Controller
@RequestMapping(value = "/secure")
public class FileUploadController extends AbstractController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IApplicationService applicationService;

	@Autowired
	private IDownloaderService downloaderService;

	private CommonsMultipartFile file;

	@RequestMapping(value = "/saveFile.html", method = RequestMethod.POST)
	public ModelAndView save(
			@ModelAttribute("uploadItem") UploadItem uploadItem, Model map,
			HttpServletResponse response, HttpServletRequest request) {

		file = (CommonsMultipartFile) uploadItem.getFile();
		final boolean decodeManifest = Boolean.valueOf(PropertyFile
				.valueOf("decode.manifest"));
		String strFilePath = file.getStorageDescription();
		int startIndex = strFilePath.indexOf("[") + 1;
		int lastIndex = strFilePath.lastIndexOf("]");
		String fileLoc = strFilePath.substring(startIndex, lastIndex).trim();
		ModelAndView mv = null;
		try {
			ApkReader apkReader = new ApkReader();
			Apk apk = apkReader.getApk(new File(fileLoc));

			Authentication auth = SecurityContextHolder.getContext()
					.getAuthentication();

			String userName = auth.getName();

			File file = new File("src/main/webapp/"
					+ PropertyFile.valueOf("user.userAps.name"));
			file.mkdir();

			file = new File("src/main/webapp/"
					+ PropertyFile.valueOf("user.userAps.name")
					+ File.separator + userName + File.separator
					+ apk.getPackageName() + File.separator
					+ apk.getVersionName());
			file.mkdirs();

			File parentDir = new File("src/main/webapp/"
					+ PropertyFile.valueOf("user.userAps.name")
					+ File.separator + userName + File.separator
					+ apk.getPackageName());
			parentDir.mkdirs();
			file = new File(parentDir, "icon.jpg");
			// Write icon
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(apk.getApkIcon());
			fos.close();
			parentDir = new File("src/main/webapp/"
					+ PropertyFile.valueOf("user.userAps.name")
					+ File.separator + userName + File.separator
					+ apk.getPackageName() + File.separator
					+ apk.getVersionName());
			// Write Apk
			file = new File(parentDir, "app.apk");
			fos = new FileOutputStream(file);
			fos.write(FileUploadController.this.file.getBytes());

			fos.close();

			Application application = applicationService
					.getApplicationByUserAndNameSpace(userName,
							apk.getPackageName());
			if (null != application) {
				mv = new ModelAndView(new RedirectView("devices.html"));
				request.getSession().setAttribute("application", application);
				ApplicationVersion appVersion = new ApplicationVersion();
				ApplicationVersionPk versionPk = new ApplicationVersionPk();

				versionPk.setApplication(application);
				versionPk.setVersion(apk.getVersionName());

				appVersion.setVersionPk(versionPk);

				appVersion
						.setVersionComment("Build #: " + apk.getVersionName());

				applicationService.saveOrUpdate(appVersion);
			} else {
				mv = new ModelAndView(new RedirectView("devices.html"));
				Application appNew = new Application();
				appNew.setApplicationName(apk.getApplicationLabel());
				appNew.setNameSpace(apk.getPackageName());
				appNew.setUser(userService.getUserByEmail(userName));
				ApplicationVersion appVersion = new ApplicationVersion();

				////////////////////////////Assigning Downloader Will be removed later///////////////////////////////
				Downloader d = new Downloader();
				d.setEmail("yahya.arshad@gmail.com");

				String email = SecurityContextHolder.getContext()
						.getAuthentication().getName();
				d.setUser(new User(email));
				d.setDeviceId("356378042257121");
				Downloader dbDownloader = downloaderService
						.getDownloaderByEmailAndDeviceId(d);
				appNew.getDownloaders().add(dbDownloader);
				
				///////////////////////////////////////////////////////////
				
				ApplicationVersionPk versionPk = new ApplicationVersionPk();

				versionPk.setApplication(appNew);
				versionPk.setVersion(apk.getVersionName());

				appVersion.setVersionPk(versionPk);

				appVersion
						.setVersionComment("Build #: " + apk.getVersionName());
				List<ApplicationVersion> appVersions = new ArrayList<ApplicationVersion>();
				appVersions.add(appVersion);
				appNew.setAppVersions(appVersions);
				applicationService.save(appNew);
				request.getSession().setAttribute("application", appNew);

			}
		} catch (Exception e) {
			e.printStackTrace();

		}

		return mv;
	}
}
